package com.neuedu.io.serializable;

import com.neuedu.utils.InputUtils;

import java.io.*;
import java.util.Date;

/**
 * @author 金山
 * 项目：javase
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2024/10/3111:21
 */
public class Runner {

    public static void main(String[] args) throws FileNotFoundException {


        //1 创建用户
        createUser();

        //使用
        // readUser();
        







    }


    //返序列化

    /***
     * User  class  发生变化了，
     */
    private static void readUser() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\upload\\user.obj"))){

            Object o = ois.readObject();

            User user = (User) o;


            System.out.println(user);

            // if("admin".equals(user.getUsername())  && "123456".equals(user.getPassword())){
            //     System.out.println("用户名密码 正确.................");
            // }else{
            //     System.out.println("错误。。。");
            // }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    private static void createUser() throws FileNotFoundException {
        String username = InputUtils.getString("请输入用户名");
        String password = InputUtils.getString("请输入密码");

        User user = new User(username,password,new Date());

        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\upload\\user.obj"))) {

            //将文件写到对象中
            /***
             * Exception in thread "main" java.lang.RuntimeException: java.io.NotSerializableException: com.neuedu.io.serializable.User
             * 	at com.neuedu.io.serializable.Runner.createUser(Runner.java:41)
             * 	at com.neuedu.io.serializable.Runner.main(Runner.java:22)
             * Caused by: java.io.NotSerializableException: com.neuedu.io.serializable.User
             * 	at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1197)
             * 	at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:354)
             * 	at com.neuedu.io.serializable.Runner.createUser(Runner.java:37)
             * 	... 1 more
             */
            //讲对象 从内存 写入到 文件中    --> 序列化    要求  对象 得实现 Serializable
            oos.writeObject(user);
            oos.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        System.out.println("user.getUsername() = " + user.getUsername());
        System.out.println("user.getPassword() = " + user.getPassword());
    }


}
